package cn.brilliantfuture.commentry.order.impl;

import java.util.Date;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import cn.brilliantfuture.commentry.entity.OrderInformation;
import cn.brilliantfuture.commentry.entity.WorkflowInfo;
import cn.brilliantfuture.commentry.order.WorkflowMessageLocal;

/**
 * 
 * Title: Cabinet Platform
 * 
 * Author:  LiTian  
 *
 * Date: 2012-7-2
 * 
 * Description:
 * 
 */
@Stateless
public class WorkflowMessageImpl implements WorkflowMessageLocal {
	
	@PersistenceContext
	EntityManager entityManager;

	@SuppressWarnings("unchecked")
	public void createWorkflowInfo(String orderCode, int workflowType, String content, Date workflowTime, String operator, int workflowModel) {
		List<OrderInformation> list = entityManager.createQuery("select oi from OrderInformation oi where oi.number = '" + orderCode + "'").getResultList();
		
		if (null != list && list.size() > 0)
			createWorkflowInfo(list.get(0), workflowType, content, workflowTime, operator, workflowModel);
	}

	@SuppressWarnings("unchecked")
	public void createWorkflowInfo(OrderInformation orderInformation, int workflowType, String content, Date workflowTime, String operator, int workflowModel) {
		List<WorkflowInfo> existList = entityManager.createQuery("select wi from WorkflowInfo wi where wi.orderInformation.orderInformationId = :orderInfoId order by wi.workflowIndex desc").setParameter("orderInfoId", orderInformation.getOrderInformationId()).getResultList();
		
		int workflowIndex = 1;
		
		if (null != existList && existList.size() > 0){
			workflowIndex = existList.get(0).getWorkflowIndex() + 1;
		} 
		
		WorkflowInfo workflowInfo = new WorkflowInfo();
		
		workflowInfo.setOrderInformation(orderInformation);
		workflowInfo.setWorkflowIndex(workflowIndex);
		workflowInfo.setContent(content);
		workflowInfo.setWorkflowTime(workflowTime);
		workflowInfo.setInsertModel(workflowModel);
		workflowInfo.setWorkflowType(workflowType);
		workflowInfo.setInsertTime(new Date());
		workflowInfo.setOperator(operator);
		workflowInfo.setDeleted(false);
		
		entityManager.persist(workflowInfo);
		entityManager.flush();
	}

	@Remove
	public void remove() {
	}

}
